/**
 * 文章子路由
 */
const express = require('express');
// 导航类目中间件
const category = require('../middleware/category');
// 文章中间件
const article = require('../middleware/article');
// 权限中间件，获取用户信息
const auth = require('../middleware/auth');
// 文章子应用
const articleApp = express();

articleApp.use(category.getList);
articleApp.use(auth.getUser);

// 文章列表页
articleApp.get('/list/:id',[article.getCategoryCount],(req,res,next)=>{
    // 用户信息，文章信息
    let {articleCount} = req;
    console.log(articleCount);
    let size = 6;
    req.page = {};
    // 文章总数
    req.page.count = articleCount;
    // 总页数
    req.page.total = Math.ceil(req.page.count/size);  
    // 当前页数
    req.page.p = req.query.p ? req.query.p : 1;
    req.page.p = req.page.p > req.page.total ? req.page.total : req.page.p;
    req.page.p = req.page.p < 1 ? 1:req.page.p;

    res.start = (req.page.p - 1)*size;
    res.size = size;
    next();
},[category.getCategoryId,article.getListCategoryId],(req,res)=>{
    let {category,articles,categoryId,user} = req;
    // 当前类目文章总数
    req.page.list = articles;
    // 所有信息
    // console.log(categoryId);
    
    if(categoryId){
        res.render('list',{category,articles,categoryId,user,page:req.page,
            title:categoryId.name
        });
    }else{
        res.render('404');
    }
});
// 文章详情页
articleApp.get('/:id',[article.getArticleById,article.getTabs,article.getPrevArticle,article.getNextArticle],(req,res)=>{
    // prev 上一页数据，next 下一页数据
    let {category,articles,tabs,prev,next,user} = req;
    res.render('article',{category,articles,tabs,prev,next,user,
        title:articles.title
    });
});
module.exports = articleApp;